#!/bin/bash
set -e

# 路径定义
DOC_DIR="/home/cyh/iommu2"
OE_KERNEL_DIR="$DOC_DIR/linux"          # OLK6.6 原始代码
COMMUNITY_KERNEL_DIR="$DOC_DIR/riscv_iommu_v7"  # 修改后的代码
PATCH_FILE="$DOC_DIR/patches/riscv_iommu.diff"
PATCH_EXCLUDES=".git .get_maintainer.ignore *.rej *.orig"

CROSS_COMPILE="riscv64-linux-gnu-"

# 1. 克隆参考分支
if [ ! -d "$COMMUNITY_KERNEL_DIR" ]; then
  echo "[1/6] Cloning community kernel..."
  git clone https://github.com/tjeznach/linux.git --depth=1 -b riscv_iommu_v7 "$COMMUNITY_KERNEL_DIR"
  cd "$COMMUNITY_KERNEL_DIR"
  b4 am https://lore.kernel.org/all/20240614142156.29420-1-zong.li@sifive.com/
  git am ./v2_20240614_zong_li_risc_v_iommu_hpm_and_nested_iommu_support.mbx
else
  echo "[1/6] Community kernel already exists, skipping clone."
fi

# 2. 生成补丁
echo "[2/6] Generating patch from OLK6.6 to community kernel..."
mkdir -p "$DOC_DIR/patches"

# 构建排除参数
exclude_args=""
for pattern in $PATCH_EXCLUDES; do
  exclude_args+="--exclude=$pattern "
done

# 在父目录生成相对路径补丁
cd "$DOC_DIR"
diff -ruN $exclude_args \
  linux/ riscv_iommu_v7/ > "$PATCH_FILE"
  
  
# 3. 应用补丁到内核
echo "[3/6] Applying patch to openEuler kernel..."
cd "$OE_KERNEL_DIR"
#git reset --hard  # 可选：回到干净状态
#git clean -fdx    # 清理无用文件
patch -p1 -N < ../patches/riscv_iommu.diff


# 4. 编译内核
echo "[4/6] Building kernel for RISC-V..."
rm -rf build
#make ARCH=riscv CROSS_COMPILE=riscv64-linux-gnu- defconfig
#make ARCH=riscv CROSS_COMPILE=riscv64-linux-gnu- -j$(nproc)
    if [[ ! -d build ]]; then
        mkdir build
        make ARCH=riscv CROSS_COMPILE=${CROSS_COMPILE} O=build -j$(nproc) defconfig
        cd build
        ARCH=riscv CROSS_COMPILE=${CROSS_COMPILE} ../scripts/kconfig/merge_config.sh .config ../../vfio.config
        cd ..
    fi
    make ARCH=riscv CROSS_COMPILE=${CROSS_COMPILE} O=build -j$(nproc) Image





